package com.xuzimian.globaldemo.jmx.mxbean;

import com.sun.jdmk.comm.HtmlAdaptorServer;
import com.xuzimian.globaldemo.jmx.standard.Hello;
import org.junit.Test;

import javax.management.*;
import java.io.IOException;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;

/**
 * JMX（Java Management Extensions，即Java管理扩展）是一个为应用程序、设备、系统等植入管理功能的框架。
 * JMX可以跨越一系列异构操作系统平台、系统体系结构和网络传输协议，灵活的开发无缝集成的系统、网络和服务管理应用。
 * @Author hzj
 * @Date 2018/3/13 18:44
 * @Description :
 */

public class QueueInspectorAgentDemo {
    private String DOMAIN_NAME = "HLMBean";
    private Integer RMI_PORT = 1099;


    public void init() throws MalformedObjectNameException, NotCompliantMBeanException, InstanceAlreadyExistsException, MBeanRegistrationException, IOException {
        Hello hello = new Hello();
        hello.setName("xzm");

        //创建并初始化 Mbean资源类
        Queue<String> queue = new ArrayBlockingQueue<>(8);
        queue.add("Request-1");
        queue.add("Request-2");
        queue.add("Request-3");
        QueueInspectorImpl queueInspector = new QueueInspectorImpl(queue);

        //为queueInspector MBean添加消息监听
        queueInspector.addNotificationListener(new QueueListener(), null, hello);

        //创建MBeanServer 容器类
        MBeanServer mBeanServer = MBeanServerFactory.createMBeanServer();
        //创建MBean资源对象的唯一名称标志
        ObjectName mbName = new ObjectName(DOMAIN_NAME, "type", "queueInfo");
        //注册MBean资源对象到MBeanServer中，并绑定唯一名称标志
        mBeanServer.registerMBean(queueInspector, mbName);
        mBeanServer.registerMBean(hello, new ObjectName("HLMBean:name=HelloWorld"));


        ObjectName adapterName = new ObjectName("jmxbean:name=htmladapter,port=8082");
        HtmlAdaptorServer adapter = new HtmlAdaptorServer();
        adapter.start();
        mBeanServer.registerMBean(adapter, adapterName);

    }

    /**
     * http://localhost:8082 访问
     *
     * @throws Exception
     */
    @Test
    public void test() throws Exception {
        init();
        Thread.sleep(Long.MAX_VALUE);
    }


}
